package com.example.app01.http

import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.lang.Exception
import kotlin.concurrent.thread

class MyOkHttp {
    private var url :String;
    private var responseData:String = ""
    constructor(url: String) {
        this.url = url
    }
    //使用post的方式提交数据并返回  后台的接口必须得使用post的方式
    /*生成form的格式作为参数提交
    * var requestBody = FormBody.Builder()
    *                   .add("username","admin)
    *                   .build()
    * */
    public fun sendRequestByPost(form:FormBody){
        thread {
            try {
                val client = OkHttpClient()
                var request = Request.Builder()
                    .url(this.url)
                    .post(form)
                    .build()
                var response = client.newCall(request).execute()
                var responseData = response.body?.string()
                if(responseData != null) {
                    this.responseData = responseData
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    //使用get发送请求
    public fun sendRequestByGet(){
        thread {
            try {
                val client = OkHttpClient()
                var request = Request.Builder()
                    .url(this.url)
                    .build()
                var response = client.newCall(request).execute()
                var responseData = response.body?.string()
                if(responseData != null) {
                    this.responseData = responseData
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    public fun getResponseData():String?{
        return this.responseData
    }
}